package com.codeplay.service.impl;

import com.codeplay.entity.User;
import com.codeplay.service.AuthService;
import com.codeplay.service.UserService;
import com.codeplay.service.JwtService;
import com.codeplay.dto.LoginRequest;
import com.codeplay.dto.LoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private UserService userService;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 验证用户名密码
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                loginRequest.getUsername(),
                loginRequest.getPassword()
            )
        );
        
        SecurityContextHolder.getContext().setAuthentication(authentication);
        
        // 获取用户信息
        User user = userService.getUserByUsername(loginRequest.getUsername());
        
        // 生成token
        String token = jwtService.generateAccessToken(user);
        String refreshToken = jwtService.generateRefreshToken(user);
        
        // 更新最后登录时间
        userService.updateLastLoginTime(user.getId());
        
        // 构建用户信息
        LoginResponse.UserInfo userInfo = LoginResponse.UserInfo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatar(user.getAvatar())
                .roles(user.getRoles().stream()
                        .map(role -> role.getName())
                        .collect(Collectors.toSet()))
                .permissions(user.getRoles().stream()
                        .flatMap(role -> role.getPermissions().stream())
                        .map(permission -> permission.getName())
                        .collect(Collectors.toSet()))
                .build();
        
        // 构建响应
        return LoginResponse.builder()
                .token(token)
                .refreshToken(refreshToken)
                .tokenType("Bearer")
                .expiresIn(3600L)
                .userInfo(userInfo)
                .build();
    }

    @Override
    public void logout(String token) {
        // 清除认证上下文
        SecurityContextHolder.clearContext();
    }

    @Override
    public String refreshToken(String refreshToken) {
        if (!jwtService.validateToken(refreshToken)) {
            throw new RuntimeException("Invalid refresh token");
        }
        
        String username = jwtService.getUsernameFromToken(refreshToken);
        User user = userService.getUserByUsername(username);
        
        return jwtService.generateAccessToken(user);
    }

    @Override
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }
        return userService.getUserByUsername(authentication.getName());
    }

    @Override
    public boolean validateToken(String token) {
        return jwtService.validateToken(token);
    }
} 